<!--示例（正式环境可删除）管理-->
<template>
  <div id="testExample" class="app-container">
    <el-alert
      title="此功能纯属为了演示系统功能，如导入、导出"
      type="error"
      :closable="false" />
    <!--搜索条件-->
    <div v-show="showSearch" class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar :show-search.sync="showSearch" create-text="新增+" :search="true" @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
          <template>
            <ImportData text="公共控制器异步导入" type="button" :list-query="listQuery" :class-name="'testExample'" @success="handleImportDataSuccess">
              <template slot="query">
                <div class="item">
                  <div class="label">测试条件：</div>
                  <el-input v-model="listQuery.number" placeholder="请输入下载数量" @keyup.enter.native="handleFilter" />
                </div>
              </template>
              <template slot="remark">
                <p>测试备注说明</p>
              </template>
            </ImportData>
            <ImportData text="本类控制器异步导入" type="button" :list-query="listQuery" :actions="['testExampleImportData','testExampleGetImportProcessStatus']" :class-name="'testExample'" @success="handleImportDataSuccess" />

          </template>
          <template slot="rightTool">
            <ImportData text="本类控制器异步导入" :list-query="listQuery" :actions="['testExampleImportData','testExampleGetImportProcessStatus']" :class-name="'testExample'" @success="handleImportDataSuccess" />
            <export-drop-down class-name="testExample" :list-query="listQuery" text="公共控制器示例（正式环境可删除）" />
            <export-drop-down class-name="testExample" :list-query="listQuery" :async="true" text="公共控制器示例（正式环境可删除）" />
            <export-drop-down class-name="testExample" :actions="['testExampleExportData','testExampleGetExportProcessStatus']" :list-query="listQuery" text="本类控制器示例（正式环境可删除）" />
            <export-drop-down class-name="testExample" :actions="['testExampleExportData','testExampleGetExportProcessStatus']" :list-query="listQuery" :async="true" text="本类控制器示例（正式环境可删除）" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="名字" prop="name" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="首字母" prop="firstLetter" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="全拼" prop="fullPinyin" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="区域代码" prop="adCode" min-width="100" sortable show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="120">
          <template slot-scope="scope">
            <button-option icon-type="svg" icon="docFileTypeWord" skin="primary" title="生成Word" @click="handleGenerateWord(scope.row)" />
            <button-option icon-type="svg" icon="docFileTypePDF" skin="primary" title="生成PDF" @click="handleGeneratePdf(scope.row)" />
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="testExampleRules"
          :model="testExampleRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="名字:" prop="name">
            <el-input v-model="testExampleRecord.name" maxlength="20" show-word-limit placeholder="请输入名字" />
          </el-form-item>
          <el-form-item label="区域代码:" prop="adCode">
            <el-input v-model="testExampleRecord.adCode" maxlength="10" show-word-limit placeholder="请输入区域代码" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      showSearch: true,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      testExampleRecord: {},
      testExampleRules: {
        name: [
          { required: true, message: '请输入名字', trigger: 'blur' }
        ],
        adCode: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('testExamplePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.testExampleRecord = {}
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增示例（正式环境可删除）'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('testExampleSave', this.testExampleRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.testExampleRecord = Object.assign({}, row) // copy obj
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑示例（正式环境可删除）'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.testExampleRecord)
          this.$store.dispatch('testExampleUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('testExampleRemove', ids).then(response => {
            this.handleFilter()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleImportDataSuccess(uuid) {
      console.log('文件保存标识：' + uuid)
      this.$modal.msgSuccess('数据导入成功!')
      this.handleFilter()
    },
    handleGeneratePdf(row) {
      this.$store.dispatch('testExampleGeneratePdf', row.id).then((response) => {
        if (response.contentType === 'blob') {
          this.T.downloadFile(response)
        }
      }).catch((_) => {
      })
    },
    handleGenerateWord(row) {
      this.$store.dispatch('testExampleGenerateWord', row.id).then((response) => {
        if (response.contentType === 'blob') {
          this.T.downloadFile(response)
        }
      }).catch((_) => {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
